#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : user.py
@Author  : different
@Time    : 2021-8-24 14:27
@Desc    : 用户模块

"""
import json

from flask import (render_template, request, flash, redirect, url_for, jsonify)
from flask_login import login_user, logout_user

from apps import cache
from apps.models.user import User
from apps.view import user_bp
from expand import login_required


@user_bp.route('/login', methods=['GET', 'POST'])
def user_loader():
    if request.method == 'POST':
        data = json.loads(request.data)
        username = data['username']
        password = data['password']
        if not username or not password:
            flash('Invalid input.')
            return redirect(url_for('user.user_loader'))
        user = User.query.filter_by(username=username).first()
        # 验证用户名和密码是否一致
        if user.validate_password(password) and login_user(user):
            return jsonify(code=200, msg="Success"), 200
        return jsonify(code=401, msg="Error"), 401
    return render_template('login.html')


@user_bp.route('/logout')
@login_required
def logout():
    cache.clear()
    logout_user()
    return redirect('/login')
